package mongo

import (
	"cgs-server/helper"
	"cgs-server/server"
	"cgs-server/server/model"
	"cgs-server/server/store"
	"errors"
	"go.mongodb.org/mongo-driver/bson"
)

type workflow struct {
	db *helper.Mongo
}

func (b *workflow) Count(filter bson.M) (int64, error) {
	return b.db.Count(server.WorkflowCollectionName, filter)
}

func (b *workflow) List(mdl *model.DataUserModel) ([]*model.Workflow, error) {
	data := mdl.Data.(*model.Workflow)

	filter := bson.M{}
	if mdl.Filter != nil {
		filter = *mdl.Filter
	}

	data.ResolveFilter(data, mdl.User, &filter)

	results := []*model.Workflow{}
	err := b.db.FindMany(server.WorkflowCollectionName, filter, &results, mdl.Options)
	if err != nil {
		return nil, err
	}
	return results, nil
}

func (b *workflow) Delete(mdl *model.Workflow, user *model.User) error {
	filter := bson.M{
		"id": mdl.ID,
	}
	mdl.ResolveFilter(mdl, user, &filter)

	_, err := b.db.DeleteOne(server.WorkflowCollectionName, filter)
	return err
}

func (b *workflow) Update(mdl *model.Workflow, user *model.User) error {
	filter := bson.M{
		"id": mdl.ID,
	}
	mdl.ResolveFilter(mdl, user, &filter)

	set := bson.M{
		"data": mdl.Data,
	}

	if mdl.Category != "" {
		set["category"] = mdl.Category
	}


	mdl.ResolveUpdateCondition(mdl, user, &set)

	update := bson.M{
		"$set": set,
	}

	_, err := b.db.UpdateOne(server.WorkflowCollectionName, filter, update)
	return err
}

func (b *workflow) Get(mdl *model.Workflow, user *model.User) (*model.Workflow, error) {

	filter := bson.M{
		"id": mdl.ID,
	}
	mdl.ResolveFilter(mdl, user, &filter)

	result := &model.Workflow{}
	find, err := b.db.FindOne(server.WorkflowCollectionName, filter, result)
	if err != nil {
		return nil, err
	}
	if !find {
		return nil, errors.New("workflow model not found")
	}

	return result, nil
}

func (b *workflow) Save(mdl *model.Workflow, user *model.User) error {
	mdl.ResolveEntity(mdl, user)
	_, err := b.db.InsertOne(server.WorkflowCollectionName, mdl)
	return err
}

func newWorkflowStore(ds *datastore) store.WorkflowStore {
	return &workflow{
		db: ds.db,
	}
}
